package com.fyzk.activity.lottery.recommend_order;

import android.os.Bundle;
import android.widget.ListView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.fyzk.base.BaseActivity;
import com.fyzk.net.Commands;
import com.fyzk.utils.AppUtil;
import com.fyzk.view.RefreshListView;
import com.fyzk.view.TopTitleView;
import com.tyjc.lottery.R;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;

import java.util.ArrayList;
import java.util.List;

import http.Common.CommandUtil;
import http.DataUtil.text.TextUtil;
import http.StringResultBean;

/**
 * <p>
 * @mood
 * @description 我的晒单
 * @author Administrator
 * @date 2018/8/4 15:18
 * </p>
 */
@ContentView(R.layout.ac_mybaskorder)
public class MyBaskOrderActivity  extends BaseActivity implements RefreshListView.OnRefreshListener {

    @ViewInject(R.id.myrecommendorder_topview)
    private TopTitleView topView;

    @ViewInject(R.id.myrr_hittatio_tv)
    private TextView hitRatio_tv;
    @ViewInject(R.id.myrr_profitratio_tv)
    private TextView profitRatio_tv;
    @ViewInject(R.id.myrr_totalWinAmount_tv)
    private TextView totalWinAmount_tv;
    @ViewInject(R.id.myrr_n_zhong_m)
    private TextView nZhongm_tv;

    @ViewInject(R.id.myrecommendorder_listview)
    private RefreshListView listView;
    private List<MyRecommendOrderBean> infos = new ArrayList<>();
    private MyRecommendOrderAdapter adapter;

    private int type = 0;   // 类型（荐单：0；跟单：1）
    private int page = 0;
    private int count = 20;
    private String mRecommendId;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        initView();

        findRecommendedUserDetail(false);
        findRecommendedUserOrders(true);
    }

    private void initView() {
        topView.setOnTitleClickListener(this);
        listView.setItemsCanFocus(false);
        listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
        listView.setOnRefreshListener(this);
        adapter = new MyRecommendOrderAdapter(getContext(), infos);
        listView.setAdapter(adapter);

        adapter.setGdUserListerner(new HisCenterAdapter.GetGdUserListen() {
            @Override
            public void getGdUser(String recommendId) {
                mRecommendId = recommendId;
                findRecommendedOrderUsers(recommendId,true);
            }
        });
    }

    /**
     * 初始化数据
     * @param userInfor
     */
    private void initData(MyRecommendBean userInfor) {
        hitRatio_tv.setText(AppUtil.formatToYuanLXS(userInfor.getHitRatio()*100)+"%");
        profitRatio_tv.setText(AppUtil.formatToYuanLXS(userInfor.getProfitRatio()*100)+"%");
        totalWinAmount_tv.setText(AppUtil.formatToYuanLXS(userInfor.getTotalWinAmount()/100)+"米");
        nZhongm_tv.setText(userInfor.getTotalCount()+"中"+userInfor.getWinCount());
    }
    /**
     * 个人荐单或跟单查询
     * @param showProgress
     */
    private void findRecommendedOrderUsers(String recommendId,boolean showProgress) {
        JSONObject request_json = new JSONObject();
        try {
            request_json.put("recommendId", recommendId);    // 类型（荐单：0；跟单：1）
            request_json.put("startLine", 0);
            request_json.put("maxLine", 20);
            httpPostJson(CommandUtil.FINDFOLLOWERSLIST, Commands.FINDFOLLOWERSLIST, request_json,
                    showProgress);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
    /**
     * 荐单个人详情查询
     * @param showProgress
     */
    private void findRecommendedUserDetail(boolean showProgress) {
        JSONObject request_json = new JSONObject();
        try {
            request_json.put("type", type);    // 类型（荐单：0；跟单：1）
            request_json.put("startLine", page);
            request_json.put("maxLine", count);
            httpPostJson(CommandUtil.FINDRECOMMENDEDUSERDETAIL, Commands.FINDRECOMMENDEDUSERDETAIL, request_json,
                    showProgress);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    /**
     * 个人荐单或跟单查询
     * @param showProgress
     */
    private void findRecommendedUserOrders(boolean showProgress) {
        JSONObject request_json = new JSONObject();
        try {
            request_json.put("type", type);    // 类型（荐单：0；跟单：1）
            request_json.put("startLine", page);
            request_json.put("maxLine", count);
            httpPostJson(CommandUtil.FINDRECOMMENDEDUSERORDERS, Commands.FINDRECOMMENDEDUSERORDERS, request_json,
                    showProgress);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onSuccess(int requestCode, StringResultBean resultBean, String result) {
        super.onSuccess(requestCode, resultBean, result);
        switch (requestCode) {
            case CommandUtil.FINDRECOMMENDEDUSERDETAIL:
                MyRecommendBean userInfor = JSON.parseObject(resultBean.getData(), MyRecommendBean.class);
                initData(userInfor);
                break;
            case CommandUtil.FINDRECOMMENDEDUSERORDERS:
                List<MyRecommendOrderBean> beans = JSON.parseArray(resultBean.getData(), MyRecommendOrderBean.class);
                if (listView.isLoadingMore) {
                    listView.hideFooterView();
                    if (beans == null || beans.size() == 0) {
                        listView.noMore();
                    } else {
                        infos.addAll(beans);
                    }
                } else {
                    infos = beans;
                    listView.hideHeaderView();
                    if (beans == null || beans.size() == 0) {
                        listView.noMore();
                    }
                }
                adapter.setInfos(infos, type);
                break;
            case CommandUtil.FINDFOLLOWERSLIST:
                List<MyRecommendOrderUserBean> bean = JSON.parseArray(resultBean.getData(), MyRecommendOrderUserBean.class);
                for (MyRecommendOrderBean info : infos) {
                    if (!TextUtil.isEmpty(mRecommendId) && info.getRecommendId().equals(mRecommendId)){
                        info.setGdUser(bean);
                        break;
                    }
                }
                adapter.setInfos(infos,type);
                break;
        }
    }

    @Override
    protected void onFailure(int requestCode, String errorCode, String message) {
        if(errorCode.equals("900003")){ // 数据为空
            if (!listView.isLoadingMore) { // 下拉刷新或第一次请求
                infos.clear();
            } else {    // 加载更多
                listView.noMore();
            }
        }
        adapter.setInfos(infos, type);
    }

    @Override
    public void onDownPullRefresh() {
        page = 0;
        findRecommendedUserOrders(false);
    }

    @Override
    public void onLoadingMore() {
        page += infos.size();
        findRecommendedUserOrders(false);
    }
}
